<template>
  <div class="login-index">
    <van-cell-group>
      <!-- .trim方法去除空格 -->
      <van-field
        v-model.trim="username"
        required
        clearable
        left-icon="contact"
        label="用户名"
        right-icon="question-o"
        placeholder="请输入用户名"
        @click-right-icon="$toast('tips: itcast')"
      />

      <van-field
        v-model.trim="password"
        type="password"
        label="密码"
        placeholder="请输入密码"
        left-icon="lock"
        required
      />
    </van-cell-group>
    <van-button
      block
      @click="handleLogin"
      size="large"
      type="primary"
      :loading="loading"
      loading-text="登录中...">登 录</van-button>

    <div class="register">
      <router-link to="/register">免费注册</router-link>
    </div>
  </div>
</template>

<script>
import qs from 'qs'
import { mobile } from '@/api'
export default {
  name: 'LoginIndex',
  data () {
    return {
      username: 'itcast',
      password: '111111',
      loading: false
    }
  },
  methods: {
    handleLogin () {
      // 在标签中添加trim属性，为空提示返回
      if (this.username === '' || this.password === '') {
        this.$toast.fail('用户名或密码不能为空')
        return
      }
      // 获取输入框的值
      let user = {
        'username': this.username,
        'password': this.password
      }
      // 正在登录
      this.loading = true
      mobile.login(user).then(res => {
        console.log(res)
        this.loading = false
        if (res.data.success) {
          this.$toast.success('登录成功')
          location.href = qs.parse(location.href.split('?')[location.href.split('?').length - 1]).repath
          // console.log(location.href.split('?')[0])
        } else {
          this.$toast.fail(res.data.message + res.data.error)
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-index {
  // text-align: center;
  padding-top: 46px;
  .van-button {
    margin: 0 auto;
    width: 90%;
    margin-top: 20px;
    background-color: #006699;
    border: 1px solid #006699;
  }
  .register {
    margin-top: 20px;
    padding-right: 20px;
    text-align: right;
    font-size: 14px;
    a {
      color: #006699;
    }
  }
}
</style>
